package com.gec.aspect;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
//@Order(value=2)
public class InjectAspect {

    private final SqlSessionFactory factory;

    public InjectAspect(SqlSessionFactory factory) {
        this.factory = factory;
    }

    private SqlSession session;

    private void getSession() {
        this.session = this.factory.openSession();
    }
    private void closeSession(){
        this.session.close();
    }
    private void commit(){
        this.session.commit();
    }


    @Before(value = "execution(* com.gec.service.Impl.*.*(..))")
    public void before() {
        getSession();
        System.out.println("{前置增强}开启事务..");
    }

    @After(value = "execution(* com.gec.service.Impl.*.*(..))")
    public void after() {
        System.out.println("{后置增强}正在执行日志..");
    }

    //定义一个方法作为切点的声明组件。[没有返回值, 没有形参, 没有内容]
    //方法名: 随意设置
    @Pointcut(value = "execution(* com.gec.service.Impl.*.*(..))")
    public void myPointCut() {
    }
    //1. pointcut="方法名()" 引用上面的切点。
    //2. Object ret 接收目标方法的返回值。
    @AfterReturning(pointcut = "myPointCut()", returning = "ret" )
    public void afterReturning(Object ret) {
//        commit();
//        closeSession();
        System.out.println("{方法返回增强}收到目标方法的返回数据:");
        System.out.println("ret = " + ret);
    }

    //异常检出增强
    @AfterThrowing(
            pointcut = "myPointCut()",
            throwing = "e"
    )
    public void checkedException(Throwable e) {
        System.out.println("{异常检出通知} e = " + e.getMessage());
    }

//    @Around(value = "myPointCut()")
//    public void around(ProceedingJoinPoint pjp) {
//        //{1}获取到传入目标方法的参数。
//        Object[] args = pjp.getArgs();
//        Object ret = null;
//        try {
//            System.out.println("{环绕增强}");
//            if ( != null) {
//                //{2}给目标方法放行..
//                System.out.println("{环绕增强}放行..");
//                ret = pjp.proceed(args);
//                System.out.println("{环绕增强}放行后");
//            } else {
//                System.out.println("{环绕增强}没有登录..");
//            }
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//    }

}
